/**
 * Created by jiachenpan on 16/11/18.
 */
import moment from 'moment'

import store from '../store'
import { getCookie} from '@/utils/cookie'

export function parseTime (time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  let time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime (time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function isExternal (path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

export function debounce (func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

export function hasBtnPermission (permission) {
  let myBtns = store.getters.btns
  let authBtn = false
  if (myBtns == null || myBtns == '' || myBtns == undefined) {
    myBtns = getCookie('btns')
  }
  myBtns = myBtns.split(';')
  myBtns.forEach(item => {
    if (item == permission || item == permission + '/**') {
      authBtn = true
    }
  })
  return authBtn
}

export function returnZore (data) {
  return data < 10 ? '0' + data : data
}

export function formatDatePicker (date) {
  /* let d = new Date(date)
  return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes()) */
  return moment(date).format('YYYY-MM-DD')
}

export function formatDateTime (date) {
  return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

export function formatDate (date) {
  /* let d = new Date(date)
   return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes()) */
  return moment(date).format('YYYY-MM-DD HH:mm')
}

export function formatTimeDate (date) {
  /* let d = new Date(date)
   return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes()) */
  return moment(date).format('HH:mm')
}

export function formatNowDate () {
  /* console.log(moment().add(1, 'hours'))
   return moment().add(1, 'hours') */
}

export function getDateBy (date) {
  /* console.log(date)
  let d = new Date(Date.parse(date.replace(/-/g,"/")))
  /!*let format2 = new Date().format('yyyy-MM-dd HH:mm:ss');
  console.log(format2)*!/
  console.log(d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate()))
  return d.getFullYear()+"-"+returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate()) */
  /* console.log(moment(date).format("YYYY-MM-DD")) */
  return moment(date).format('YYYY-MM-DD')
}

export function getRangeDate (date) {
  return moment(date).format('MM-DD HH:mm')
  /* let d = new Date(date)
  return returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes()) */
}

export function isBeforeDate (date, nData) {
  let d = moment(date).format('YYYY-MM-DD HH:mm:ss')
  let n = ''
  if (nData) {
    n = moment(nData).format('YYYY-MM-DD HH:mm:ss')
  } else {
    n = moment().format('YYYY-MM-DD HH:mm:ss')
  }
  return moment(d).isBefore(n)
  /* let d = new Date(date)
   return returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes()) */
}

export function getCurrDateMoment () {
  return moment().format('YYYY-MM-DD')
  /* let d = new Date(date)
   return returnZore(d.getMonth()+1)+"-"+returnZore(d.getDate())+" "+returnZore(d.getHours())+":"+returnZore(d.getMinutes()) */
}

export function toDateMoment (date) {
  return moment(date).format()
}

export function isAuth (data) {
  let role = ['普通用户', '会议室预约管理员', '公务班', '警卫班', '会议室管理员']
  let result = role.filter(item => data == item)
  if (result.length > 0) {
    return true
  }
  return false
}

export function compare (property) {
  return function (a, b) {
    let value1 = a[property]
    let value2 = b[property]
    return value1 - value2
  }
}

export function compareOrg (property) {
  return function (a, b) {
    let value1 = a[property]
    let value2 = b[property]
    if (value1 == value2) {
      return isBeforeDate(a['createdTime'], b['createdTime']) == true ? 1 : -1
    } else {
      return value2 - value1
    }
  }
}

export function compareTime (property) {
  return function (a, b) {
    let value1 = a[property]
    let value2 = b[property]
    return isBeforeDate(value1, value2) == true ? -1 : 1
  }
}

export function returnNewData (data) {
  let result = {}
  for (let property in data) {
    result[property] = data[property]
  }
  return result
}
